package com.feicheng.iou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.entity.Interview;
import com.feicheng.iou.mapper.InterviewMapper;
import com.feicheng.iou.pojo.lifeCyclePOJO.InterviewAndBackviewPOJO;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.pojo.login.PermissionLevelTwoPOJO;
import com.feicheng.iou.pojo.login.PermissionListPOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.commom.ReturnCode;
import com.feicheng.iou.constant.StatuConstant;
import com.feicheng.iou.entity.*;
import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.mapper.*;
import com.feicheng.iou.pojo.InterviewPOJO;
import com.feicheng.iou.pojo.ResultInterviewPOJO;
import com.feicheng.iou.service.InterviewService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.feicheng.iou.util.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.swing.table.TableRowSorter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
@Setter
public class InterviewServiceImpl extends ServiceImpl<InterviewMapper, Interview> implements InterviewService {

    @Autowired
    private InterviewMapper interviewMapper;  //接待映射

    @Autowired
    private InterviewAndBackviewPOJO interviewAndBackviewPOJO; //封装接待和其回访列表

    @Autowired
    private ResourceMapper resourceMapper; //

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ResourceRecordMapper resourceRecordMapper;

    @Autowired
    private ReservationBackviewMapper reservationBackviewMapper;

    @Autowired
    private ReservationTryMapper reservationTryMapper;

    /**
     * @Author wuweinan
     * @Description 根据学生id查询接待信息.
     * @Date 2021-7-2 9:11
     * @param studentId
     * @return void
     */
    @Override
    public ResultInfo selectInterviewByStudentId(Integer studentId) { //void
        log.info("InterviewServiceImpl的selectInterviewByStudentId方法进入");

        //根据学生Id查询接待信息
        QueryWrapper<Interview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Interview interview = interviewMapper.selectOne(queryWrapper);

        //封装信息
        interviewAndBackviewPOJO.setInterview(interview);
        log.info("InterviewServiceImpl的selectInterviewByStudentId方法返回");
        return ResultInfo.success(interview);

    }


    /*
     * @Author luoxin
     * @Description //处理添加到访线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  interviewPOJO 线索的POJO包含 Resource Student ResourceRecord
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo insert(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类insert进入,参数为: " + interviewPOJO);

        /* 解析POJO封装到entity */
        Interview interview = interviewPOJO.getInterview(); //解析intereview
        Integer studentId = interviewPOJO.getStudent().getId();//解析Student中 学生id
        Resource resource = interviewPOJO.getResource();//解析Resource
        ReservationBackview reservationBackview = new ReservationBackview();
        ReservationTry reservationTry = new ReservationTry();
        String ypzw = resource.getYpzw();//解析Resource应聘职位
        interview.setStudentId(studentId); //将学生id封装进interview
        interview.setYpzw(ypzw);//将ypzw封装进interview

        //处理interview添加，调用mapper
        int insertInterviewResult = interviewMapper.insert(interview);
        //验证是否成功插入interview
        if (insertInterviewResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_INSERT_FAIL);
        }

        //修改resource的Statu为到访待回访
        resource.setStatu(StatuConstant.DAOFANGDAIHUIFANG);
        //根据获取resource的ID修改推进状态
        int updateResourceResult = resourceMapper.updateById(resource);
        //验证是否成功修改线索推进状态
        if (updateResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_STATU_UPDATE_FAIL);
        }

        //取到插入线索的stageId
        reservationBackview.setStageId(2);
        //取到插入的studentID
        reservationBackview.setStudentId(studentId);
        //处理reservationBackview添加，调用mapper
        int insertReservationBackview = reservationBackviewMapper.insert(reservationBackview);
        //当插入失败插入resourceRecord
        if (insertReservationBackview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        //取到插入的studentID
        reservationTry.setStudentId(studentId);
        //处理reservationInterview添加，调用mapper
        int insertReservationTry = reservationTryMapper.insert(reservationTry);
        //验证是否成功插入resourceRecord
        if (insertReservationTry == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        log.info("InterviewServiceImpl类insert结束");
        return ResultInfo.success();
    }



    /*
     * @Author luoxin
     * @Description //处理修改到访线索的业务的service实现类
     * @Date 下午3:29 2021/6/30
     * @Param interviewPOJO 包含 Interview Resource Student ResourceRecord ReservationBackview ReservationTry
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo update(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类update进入,参数为: " + interviewPOJO);

        //解析POJO封装到entity
        Interview interview = interviewPOJO.getInterview();//解析intereview
        Student student = interviewPOJO.getStudent();//解析Student
        Resource resource = interviewPOJO.getResource();//解析Resource
        ResourceRecord resourceRecord = interviewPOJO.getResourceRecord();//解析ResourceRecord
        ReservationBackview reservationBackview = interviewPOJO.getReservationBackview();//解析reservationBackview
        ReservationTry reservationTry = interviewPOJO.getReservationTry();//解析reservationTry

        //处理interview修改，调用mapper
        int updateInterviewByIdResult = interviewMapper.updateById(interview);
        //验证是否成功修改interview信息
        if (updateInterviewByIdResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_UPDATE_FAIL);
        }

        //处理student修改，调用mapper
        int updateStudentByIdResult = studentMapper.updateById(student);
        //验证是否成功修改student信息
        if (updateStudentByIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_UPDATE_FAIL);
        }

        //处理resource修改，调用mapper
        int updateResourceByIdResult = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (updateResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        //处理resourceRecord修改，调用mapper
        int updateResourceRecordRByIdResult = resourceRecordMapper.updateById(resourceRecord);
        //验证是否成功修改resourceRecord信息
        if (updateResourceRecordRByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_UPDATE_FAIL);
        }


        if(interviewPOJO.getReservationBackview().getDatetime() != null) {
            //处理reservationBackview修改，调用mapper
            int updateReservationBackviewByIdResult = reservationBackviewMapper.updateById(reservationBackview);
            //验证是否成功修改reservationBackview信息
            if (updateReservationBackviewByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_UPDATE_FAIL);
            }
        }


        if(interviewPOJO.getReservationTry().getDatetime() != null) {
            //处理reservationTry修改，调用mapper
            int updateReservationTryByIdResult = reservationTryMapper.updateById(reservationTry);
            //验证是否成功修改reservationTry信息
            if (updateReservationTryByIdResult == 0) {
                throw new SystemException(ReturnCode.RESERVATIONTRY_UPDATE_FAIL);
            }
        }

        log.info("InterviewServiceImpl类update结束");
        return ResultInfo.success();
    }



    /*
     * @Author luoxin
     * @Description //处理删除到访线索的业务的service实现类
     * @Date 下午9:30 2021/7/1
     * @Param interviewPOJO 包含 Interview Resource Student ResourceRecord ReservationBackview ReservationTry
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo delete(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类delete进入,参数为: " + interviewPOJO);

        //解析POJO封装到entity
        Integer interviewId = interviewPOJO.getInterview().getId();//解析interview中ID
        Integer studentId = interviewPOJO.getStudent().getId();//解析Student
        Integer resourceId = interviewPOJO.getResource().getId();//解析Resource
        Integer resourceRecordId = interviewPOJO.getResourceRecord().getId();//解析ResourceRecord
        Integer reservationBackviewId = interviewPOJO.getReservationBackview().getId();//解析reservationBackview
        Integer reservationTryId = interviewPOJO.getReservationTry().getId();//解析reservationTry

        //处理interview删除，调用mapper
        int deleteInterviewbyIdResult = interviewMapper.deleteById(interviewId);
        //验证是否成功删除interview信息
        if (deleteInterviewbyIdResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_DELETE_FAIL);
        }

        //处理student删除，调用mapper
        int deleteStudentbyIdResult = studentMapper.deleteById(studentId);
        //验证是否成功删除student信息
        if (deleteStudentbyIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_DELETE_FAIL);
        }

        //处理resource删除，调用mapper
        int deleteResourceByIdResult = resourceMapper.deleteById(resourceId);
        //验证是否成功删除resource信息
        if (deleteResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_DELETE_FAIL);
        }

        //处理resourceRecord删除，调用mapper
        int deleteResourceRecordByIdResult = resourceRecordMapper.deleteById(resourceRecordId);
        //验证是否成功删除resourceRecord信息
        if (deleteResourceRecordByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_DELETE_FAIL);
        }

        //处理reservationBackview删除，调用mapper
        int deleteReservationBackviewByIdResult = reservationBackviewMapper.deleteById(reservationBackviewId);
        //验证是否成功删除reservationBackview信息
        if (deleteReservationBackviewByIdResult == 0) {
            throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_DELETEE_FAIL);
        }

        //处理reservationTry删除，调用mapper
        int deleteReservationTryByIdResult = reservationTryMapper.deleteById(reservationTryId);
        //验证是否成功删除reservationTry信息
        if (deleteReservationTryByIdResult == 0) {
            throw new SystemException(ReturnCode.RESERVATIONTRY_DELETE_FAIL);
        }

        log.info("InterviewServiceImpl类delete结束");
        return ResultInfo.success();
    }



    /*
     * @Author luoxin
     * @Description //处理查询到访线索列表的业务的service实现类
     * @Date 下午3:29 2021/6/30
     * @Param interviewPOJO 包含 Interview Resource Student ResourceRecord ReservationBackview ReservationTry
     * @return ResultInfo
     */
    @Override
    public ResultInfo listAll(InterviewPOJO interviewPOJO, HttpServletRequest request) {
        log.info("InterviewServiceImpl类listAll进去，参数为" + interviewPOJO);

        //定义一个放返回数据的Map
        HashMap<Object, Object> resultMap = new HashMap<>();
        //获取传入数据中的pege当前页，size每页条数得出当前页起始数据索引
        Integer pageIndex = PageUtil.getPageIndex(interviewPOJO.getPage(), interviewPOJO.getSize());
        //把数据索引封装到interviewPOJO
        interviewPOJO.setPageIndex(pageIndex);
        //检查是否拥有可分配权限，根据用户不同显示不同的数据
        LoginReturnPOJO loginReturnPOJO = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        List<PermissionListPOJO> permissions = loginReturnPOJO.getPermissions();

        //定一个boolean的变量校验权限是否为可分配
        boolean kefenpeiFlag = false;
        for (PermissionListPOJO permissionListPOJO : permissions) {
            List<PermissionLevelTwoPOJO> permissionsTwo = permissionListPOJO.getPermissions();
            for (PermissionLevelTwoPOJO permissionLevelTwoPOJO : permissionsTwo) {
                if (permissionLevelTwoPOJO.getName().equals("可分配")) {
                    kefenpeiFlag = true;
                    break;  //如何退出两层for需调研
                }
            }
        }

        if (interviewPOJO.getInterview().getAutor() == null) {
            if (kefenpeiFlag) {
                interviewPOJO.getInterview().setAutor(null);
            } else {
                interviewPOJO.getInterview().setAutor(loginReturnPOJO.getUser().getUserId());
            }
        }
        //调用Mapper中查询条数的方法得出条数封装进interviewPOJO
        interviewPOJO.setTotal(interviewMapper.queryInterviewAllCount(interviewPOJO));
        //根据传入的pojo查询，结果封装到interviewPOJOSList
        List<ResultInterviewPOJO> resultInterviewPOJOList = interviewMapper.queryInterviewAll(interviewPOJO);
        //获取pageutil里的pageinfo里的数据封装到pageinfo这个map
        Map<String, Integer> pageInfo = PageUtil.getPageInfo(interviewPOJO.getPage(), interviewPOJO.getSize(), interviewPOJO.getTotal());
        //把pageinnfo这个map封装到resultMap中
        resultMap.put("pageInfo", pageInfo);
        //把resourcePOJOSList这个list封装到resultMap中
        resultMap.put("list", resultInterviewPOJOList);
        //把resultMap封装到ResultInfo中
        ResultInfo success = ResultInfo.success(resultMap);

        log.info("InterviewServiceImpl类listAll结束");
        return success;
    }

    /*
     * @Author luoxin
     * @Description //处理查询单个到访线索的业务的service实现类
     * @Date 下午3:29 2021/6/30
     * @Param interviewPOJO 包含 Interview Resource Student ResourceRecord ReservationBackview ReservationTry
     * @return ResultInfo
     */
    @Override
    public ResultInfo selectinfo(Integer id) {
        log.info("interviewServiceImpl类selectinfo进入，进入数据为" + id);

        //定义一个放返回数据的Map
        Map<String, Object> resultMap = new HashMap<>();
        //定义一个存放studentID的map
        HashMap<String, Object> studentIdList = new HashMap<String, Object>();
        //定义一个存放resourceID的map
        HashMap<String, Object> resourceIdMap = new HashMap<String, Object>();
        //根据interviewID查找，取到studentID
        Integer studentId = interviewMapper.selectById(id).getStudentId();
        //把查到的学生ID封装到map中
        studentIdList.put("student_Id", studentId);
        //把resourceID封装到resourceIdMap中
        resourceIdMap.put("resource_Id", resourceMapper.selectByMap(studentIdList).get(0).getId());

        //将所有查询到的信息封装到返回信息的map中
        resultMap.put("interview", interviewMapper.selectById(id));
        resultMap.put("resourceRecord", resourceRecordMapper.selectByMap(resourceIdMap).get(0));
        resultMap.put("resource", resourceMapper.selectByMap(studentIdList).get(0));
        resultMap.put("student", studentMapper.selectById(studentId));

        //判断查询结果是不是为空，如果为空map中reservationBackview赋值空对象，不为空将信息封装到map中
        if (reservationBackviewMapper.selectByMap(studentIdList).size() != 0){
            resultMap.put("reservationBackview", reservationBackviewMapper.selectByMap(studentIdList).get(0));
        }else{
            resultMap.put("reservationBackview", new ReservationBackview());
        }

        //判断查询结果是不是为空，如果为空map中reservationTry赋值空对象，不为空将信息封装到map中
        if (reservationTryMapper.selectByMap(studentIdList).size() != 0){
            resultMap.put("reservationTry", reservationTryMapper.selectByMap(studentIdList).get(0));
        }else{
            resultMap.put("reservationTry", new ReservationTry());
        }

        //把resultMap封装到ResultInfo中
        ResultInfo resultInfo = ResultInfo.success(resultMap);

        log.info("InterviewServiceImpl类selectinfo结束");
        return resultInfo;
    }


    /*
     * @Author luoxin
     * @Description //处理到访管理分配线索的业务的service实现类
     * @Date 下午3:29 2021/6/30
     * @Param interviewPOJO 包含 Interview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo updateAutor(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类updateAutor进入,参数为: " + interviewPOJO);

        //解析POJO封装到entity
        Interview interview = interviewPOJO.getInterview();//解析Interview
        Integer userId = interviewPOJO.getUser().getUserId();//解析User中ID

        //处理interview修改，调用mapper
        interview.setAutor(userId);
        int updateInterviewByIdResult = interviewMapper.updateById(interview);
        //验证是否成功修改interview信息
        if (updateInterviewByIdResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_UPDATE_FAIL);
        }

        log.info("InterviewServiceImpl类updateAutor结束");
        return ResultInfo.success();

    }

    @Override
    public ResultInfo abandonInterview(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类abandon进入");

        //解析POJO封装到entity
        Resource resource = interviewPOJO.getResource();//解析Resource

        //修改线索推进状态为已放弃
        resource.setStatu(StatuConstant.YIFANGQI);
        //处理resource修改，调用mapper
        int abandonResourceResult = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (abandonResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        log.info("InterviewServiceImpl类abandon结束");
        return ResultInfo.success();
    }

    @Override
    public ResultInfo updateFlg(InterviewPOJO interviewPOJO) {
        log.info("InterviewServiceImpl类updateFlg进入,参数为: " + interviewPOJO);

        //解析POJO封装到entity
        Interview interview = interviewPOJO.getInterview();//解析Interview

        //处理interview修改，调用mapper
        int updateInterviewByIdResult = interviewMapper.updateById(interview);
        //验证是否成功修改interview信息
        if (updateInterviewByIdResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_UPDATE_FAIL);
        }

        log.info("InterviewServiceImpl类updateFlg结束");
        return ResultInfo.success();
    }
}
